package reaction.utils.xml;

import java.io.IOException;
import java.io.StringReader;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.xml.sax.InputSource;

import org.apache.commons.httpclient.Credentials;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.HttpVersion;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.UsernamePasswordCredentials;
import org.apache.commons.httpclient.auth.AuthScope;
import org.apache.commons.httpclient.methods.GetMethod;


public class XMLUtils {
	
	public static Document loadXMLFromString(String xml) throws Exception {
		
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        InputSource is = new InputSource(new StringReader(xml));
        return builder.parse(is);
    }
	
	public static Document getXML(String id, String category) throws IOException {
	
		try {			
	        //create a singular HttpClient object
	        HttpClient client = new HttpClient();

	        //establish a connection within 5 seconds
	        client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
	        client.getParams().setParameter("http.protocol.version", HttpVersion.HTTP_1_1);
	        client.getParams().setParameter("http.socket.timeout", new Integer(1000));
	        client.getParams().setParameter("http.protocol.content-charset", "UTF-8");
	        
	        client.getParams().setAuthenticationPreemptive(true);
	        Credentials defaultcreds = new UsernamePasswordCredentials("publico", "publ1c0");
	        client.getState().setCredentials(new AuthScope("reactionvm01.inesc-id.pt", 80, AuthScope.ANY_REALM), defaultcreds);

	        String url = "http://reactionvm01.inesc-id.pt/news-feeds/index.psp?";
	        HttpMethod method = null;

	        //create a method object
	        method = new GetMethod(url);
	        method.setFollowRedirects(true);
	            
	        NameValuePair[] params = new NameValuePair[2];
	            
	        params[0] = new NameValuePair("id",id); 
	        params[1] = new NameValuePair("category", category);	            
	            
	        method.setQueryString(params);
	        
	        //execute the method
	        String responseBody = null;
	        try{
	            client.executeMethod(method);
	            responseBody = method.getResponseBodyAsString();
	        } catch (HttpException he) {
	            System.err.println("Http error connecting to '" + url + "'");
	            System.err.println(he.getMessage());
	            System.exit(-4);
	        } catch (IOException ioe){
	            System.err.println("Unable to connect to '" + url + "'");
	            System.exit(-3);
	        }
	        
	        /*
	        //write out the request headers
	        System.out.println("*** Request ***");
	        System.out.println("Request Path: " + method.getPath());
	        System.out.println("Request Query: " + method.getQueryString());
	        Header[] requestHeaders = method.getRequestHeaders();
	        for (int i=0; i<requestHeaders.length; i++){
	            System.out.print(requestHeaders[i]);
	        }

	        
	        //write out the response headers
	        System.out.println("*** Response ***");
	        System.out.println("Status Line: " + method.getStatusLine());
	        Header[] responseHeaders = method.getResponseHeaders();
	        for (int i=0; i<responseHeaders.length; i++){
	            System.out.print(responseHeaders[i]);
	        }
	         */
	        

	        //write out the response body
	        //System.out.println("*** Response Body ***");
	        
	        //clean up the connection resources
	        method.releaseConnection();
	        
	        //System.out.println(responseBody.trim());
	        //System.out.println(url+"id?"+id+"&category="+category);
	        Document doc = XMLUtils.loadXMLFromString(responseBody.trim());	        
	        
	        return doc;
	        
		} catch (Exception e) {
			System.out.println(e);
		}		
		return null;
	}

}
